﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace MyRaceGame.GameLogic
{
    public class NameDisplayedRacerCharacter : RacerDecorator
    {
        public NameDisplayedRacerCharacter(RacerCharacter skinnedModel, RaceGame raceGame)
            : base(skinnedModel)
        {
            this.raceGame = raceGame;

            Vector2 size = raceGame.Font.MeasureString(skinnedModel.Name);

            headText = new RenderTarget2D(raceGame.GraphicsDevice,
                    (int)size.X, (int)size.Y , true, raceGame.GraphicsDevice.DisplayMode.Format,
                    DepthFormat.Depth24, 1, RenderTargetUsage.PreserveContents);

            raceGame.GraphicsDevice.SetRenderTarget(headText);

            raceGame.SpriteBatch.Begin();

            raceGame.SpriteBatch.DrawString(raceGame.Font, skinnedModel.Name, Vector2.Zero, Color.Red);

            raceGame.SpriteBatch.End();

            raceGame.GraphicsDevice.SetRenderTarget(null);

            nameDrawer = new QuadDrawer(raceGame.GraphicsDevice);
        }

        public void ResetDisplayNameTexture()
        {
            Vector2 size = raceGame.Font.MeasureString(racerCharacter.Name);

            headText = new RenderTarget2D(raceGame.GraphicsDevice,
                    (int)size.X, (int)size.Y, true, raceGame.GraphicsDevice.DisplayMode.Format,
                    DepthFormat.Depth24, 1, RenderTargetUsage.PreserveContents);

            raceGame.GraphicsDevice.SetRenderTarget(headText);

            raceGame.SpriteBatch.Begin();

            raceGame.SpriteBatch.DrawString(raceGame.Font, racerCharacter.Name, Vector2.Zero, Color.Red);

            raceGame.SpriteBatch.End();

            raceGame.GraphicsDevice.SetRenderTarget(null);

            nameDrawer = new QuadDrawer(raceGame.GraphicsDevice);
        }

        protected override void ExtraDrawing(Matrix view, Matrix projection, Vector3 cameraPosition)
        {
            Matrix world = Matrix.CreateTranslation(0, 5.5f, 3) *
                           Matrix.CreateScale(textScale) *
                           Matrix.CreateConstrainedBillboard(Position, cameraPosition,
                                                             Vector3.Up, null, null);

            nameDrawer.DrawQuad(headText, 1, world, view, projection);
        }

        RaceGame raceGame;
        readonly int textScale = 80;
        RenderTarget2D headText;
        QuadDrawer nameDrawer;
    }
}
